"""
Case Type   : cm_agent参数
Case Name   : incremental_build功能验证，设置参数为off，观察是否为全量重建备机
Create At   : 2025/4/3
Owner       : ningyali
Description :
    1.查询参数incremental_build默认值
    2.修改参数值为off
    3.重启集群使参数生效
    4.stop备机
    5.重建备机
    6.查看gs_ctl日志，日志包含如下信息
Expect      :
    1.执行成功
    2.执行成功
    3.执行成功
    4.执行成功
    5.执行成功
    6.执行成功
History     :
"""

import os
import time
import unittest

from testcase.utils.ComInstall import CmInstall
from testcase.utils.ComInstall import CmUnInstall
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class CMServer(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.root_nodes = (Node('PrimaryRoot'), Node('Standby1Root'),
                           Node('Standby2Root'))
        self.user_nodes = (Node('PrimaryDbUser'), Node('Standby1DbUser'),
                           Node('Standby2DbUser'))
        self.common = Common()
        self.log_path = os.path.join(
            macro.GAUSSDB_LOG_PATH, self.user_nodes[0].ssh_user,
            'bin', 'gs_ctl')

        text = '----prestep1:安装cm;expect:执行成功----'
        self.log.info(text)
        self.install_pkg_path = os.path.dirname(macro.DB_SCRIPT_PATH)
        self.cm = CmInstall(self.install_pkg_path, self.pri_sh.node.ssh_user)
        res = self.cm.update_xml_for_cm(*self.root_nodes)
        self.assertGreater(res.count('cmDir'), 1, f'执行失败: {text}')

        res = self.cm.cm_install(self.user_nodes[0])
        self.assertIn('Install CM tool success', res, f'执行失败: {text}')

        text = '----prestep2:备份gs_ctl日志文件;expect:执行成功----'
        self.log.info(text)
        bak_cmd = f'cd {self.log_path};' \
                  f'ls|grep ".log"|xargs -I {{{{}}}} ' \
                  f'mv {{{{}}}} {{{{}}}}.bak; ls'
        bak_res = self.common.get_sh_result(self.user_nodes[1], bak_cmd)
        self.assertNotIn('error', bak_res.lower(), f'执行失败: {text}')

    def test_trans(self):
        text = '----step1:查询参数incremental_build默认值;expect:执行成功----'
        self.log.info(text)
        q_logdir_cmd = f"source {macro.DB_ENV_PATH};" \
                       f"cm_ctl list --param --agent | grep incremental_build"
        q_res = self.common.get_sh_result(self.user_nodes[0], q_logdir_cmd)
        self.assertIn('incremental_build = on', q_res, f'执行失败: {text}')

        text = '----step2:修改参数值为off;expect:执行成功----'
        self.log.info(text)
        set_cmd = f"source {macro.DB_ENV_PATH};" \
                  f"gs_guc set -Z cmagent -N all -I all -c " \
                  f"incremental_build=\"off\""
        set_res = self.common.get_sh_result(self.user_nodes[0], set_cmd)
        self.assertIn(
            'ALL: Success to perform gs_guc!', set_res, f'执行失败: {text}')

        text = '----step3:重启集群使参数生效;expect:执行成功----'
        self.log.info(text)
        restart_cmd = f"source {macro.DB_ENV_PATH};cm_ctl stop && cm_ctl start"
        restart_res = self.common.get_sh_result(self.user_nodes[0], restart_cmd)
        self.assertEqual(restart_res.count('cluster successfully'), 2,
                         f'执行失败: {text}')
        time.sleep(5)

        text = '----step4:stop备机;expect:执行成功----'
        self.log.info(text)
        stop_cmd = f'source {macro.DB_ENV_PATH};' \
                   f'cm_ctl stop -n 2 -D {macro.DB_INSTANCE_PATH}'
        stop_res = self.common.get_sh_result(self.user_nodes[0], stop_cmd)
        self.assertIn(
            'cm_ctl: stop instance successfully', stop_res, f'执行失败: {text}')

        text = '----step5:重建备机;expect:执行成功----'
        self.log.info(text)
        build_cmd = f'source {macro.DB_ENV_PATH};' \
                    f'cm_ctl build -n 2 -D {macro.DB_INSTANCE_PATH}'
        build_res = self.common.get_sh_result(self.user_nodes[0], build_cmd)
        self.assertIn(
            'cm_ctl: build successfully', build_res, f'执行失败: {text}')

        text = '----step6:查看gs_ctl日志，日志包含如下信息;expect:执行成功----'
        self.log.info(text)
        expect = 'set gaussdb state file when full build build:' \
                 'db state(BUILDING_STATE), server mode(STANDBY_MODE), ' \
                 'build mode(FULL_BUILD).'
        grep_cmd = f'source {macro.DB_ENV_PATH};' \
                   f'cd {self.log_path}; ls -l; ' \
                   f'grep -i "full build" *.log'
        grep_res = self.common.get_sh_result(self.user_nodes[1], grep_cmd)
        self.assertIn(expect, grep_res, f'执行失败: {text}')

    def tearDown(self):
        text = '----poststep1:卸载cm;expect:执行成功----'
        self.log.info(text)
        self.un_cm = CmUnInstall(self.install_pkg_path,
                                 self.pri_sh.node.ssh_user)
        res = self.un_cm.cm_uninstall(
            self.user_nodes[0], '--deleteData --deleteBinary')
        self.assertIn('Uninstall CM tool success', res, f'执行失败: {text}')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
